package com.santana.parser;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Version;

import com.santana.icine.Response;

public class Lucene {

	private static Logger log = Logger.getLogger(Lucene.class);
	public static Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_44);

	public Response getMovies(String city, Directory directory) {

		Response response = new Response();
		
		try {
			IndexReader reader = IndexReader.open(directory);
			IndexSearcher searcher = new IndexSearcher(reader);

			int hitsPerPage = 100;
			
			Query q = new QueryParser(Version.LUCENE_44, "city", analyzer).parse(city);
			
			TopDocs topDocs = searcher.search(q, hitsPerPage);
			ScoreDoc[] hits = topDocs.scoreDocs;
			
			List<String> movies = new ArrayList<String> ();
						
			System.out.println("Found " + hits.length + " hits.");
			for (int i = 0; i < hits.length; ++i) {
				int docId = hits[i].doc;
				Document d = searcher.doc(docId);
				System.out.println((i + 1) + ". " + d.get("city") + "\t" + d.get("movie"));
				movies.add(d.get("movie"));
			}
			

		} catch (Exception e) {
			log.error(e);
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		
		return response;
	}

}
